import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_utils/const.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';

import '../../../hj_model/video_model.dart';
import '../../../hj_utils/global.dart';
import '../../../tools_base/video_download/video_download_manager.dart';
import '../../../tools_base/video_download/video_load_record.dart';

class VideoCacheLogic extends GetxController with GetTickerProviderStateMixin {
  List<String> get typeTitle => ['影视', '抖音', '动漫'];
  late final TabController controller = TabController(length: typeTitle.length, vsync: this);

  List<VideoModel> get allVideoList {
    return [...longList, ...shortList, ...cartoonList];
  }

  List<VideoModel> longList = [];
  List<VideoModel> shortList = [];
  List<VideoModel> cartoonList = [];

  bool isEditing = false;
  DownloadCallBack? _callBack;

  RxBool isLoadingData = true.obs;

  @override
  void onInit() {
    super.onInit();

    _callBack = DownloadCallBack(
      success: (url) {
        for (VideoModel item in allVideoList) {
          if (item.realVideoUrl == url) {
            item.loadProgress = "100.00";
            update();
            break;
          }
        }
        //showToast( "视频下载完成");
        update();
      },
      fail: (url, error) {
        for (VideoModel item in allVideoList) {
          if (item.realVideoUrl == url) {
            item.isLoaderRunning = "0";
            break;
          }
        }
        showToast("缓存加载失败");
        update();
      },
      progress: (url, progress) {
        for (VideoModel item in allVideoList) {
          if (item.realVideoUrl == url) {
            item.loadProgress = progress;
            // item.isLoaderRunning = "1";
            break;
          }
        }
        update();
      },
    );
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _loadData();
    });
  }

  void _loadData() async {
    try {
      longList = await VideoLoadRecord.instance.getMovieCacheVideoList(CacheMediaType.video);
      shortList = await VideoLoadRecord.instance.getMovieCacheVideoList(CacheMediaType.short);
      cartoonList = await VideoLoadRecord.instance.getMovieCacheVideoList(CacheMediaType.cartoon);

      for (VideoModel item in allVideoList) {
        dynamic result = await VideoDownloadManager.instance.searchInfo(
          url: item.realVideoUrl,
          callBack: _callBack,
        );
        if (result is Map) {
          Map localInfo = result;
          debugLog(localInfo);
          item.localPath = localInfo["localPath"];
          item.loadProgress = localInfo["progress"];
          item.isLoaderRunning = localInfo["isLoaderRunning"];
        }
      }
    } catch (e) {
      debugLog(e);
    }
    update();
    isLoadingData.value = false;
  }

  void editEvent() async {
    if (!isEditing) {
      //编辑
      isEditing = !isEditing;
      update();
    } else {
      // 删除
      List<VideoModel> deleteArr = [];
      for (VideoModel item in allVideoList) {
        if (item.isSelected) {
          deleteArr.add(item);
          await VideoDownloadManager.instance.delete(item.realVideoUrl);
        }
      }

      if (deleteArr.isNotEmpty) {
        await VideoLoadRecord.instance.removeVideoListNoType(deleteArr);
        for (VideoModel item in deleteArr) {
          longList.remove(item);
          shortList.remove(item);
          cartoonList.remove(item);
        }
      }
      isEditing = !isEditing;
      update();
    }
  }

  void loadStartOrStopEvent(VideoModel videoModel) async {
    if (videoModel.isLoaderRunning == "1") {
      await VideoDownloadManager.instance.pause(videoModel.realVideoUrl);
      videoModel.isLoaderRunning = "0";
    } else {
      for (var item in allVideoList) {
        if (item.isLoaderRunning == "1") {
          await VideoDownloadManager.instance.pause(videoModel.realVideoUrl);
          item.isLoaderRunning = "0";
        }
      }
      dynamic result = await VideoDownloadManager.instance.download(
        url: videoModel.realVideoUrl,
        callBack: _callBack,
      );
      if (result != null) {
        debugLog("download movie file: $result");
      } else {
        videoModel.isLoaderRunning = "1";
      }
    }
    update();
  }

  @override
  void onClose() {
    VideoDownloadManager.instance.removeAllCallBack();
    super.onClose();
  }
}
